package org.example.springlogin.service;

import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.example.springlogin.controller.CaptchaController;
import org.example.springlogin.mapper.UserMapper;
import org.example.springlogin.model.UserInfo;
import org.example.springlogin.utils.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 九转苍翎
 * Date: 2025/10/14
 * Time: 14:41
 */
@Service
@Slf4j
public class UserService {

    private final UserMapper userMapper;

    @Autowired
    public UserService(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    public String getUserInfoByUserName(String userName, String password, String captcha, HttpSession session) {
        UserInfo userInfo = userMapper.getUserInfoByUserName(userName);
        if (userInfo == null) {
            log.info("用户不存在");
            return "用户不存在";
        }
        if (!SecurityUtil.verify(password,userInfo.getPassword())) {
            log.info("密码错误");
            return "密码错误";
        }
        long saveTime = (long)session.getAttribute("CAPTCHA_SESSION_DATE");
        if (System.currentTimeMillis() - saveTime > CaptchaController.delay) {
            log.info("验证码超时");
            return "验证码超时";
        }
        if (!captcha.equalsIgnoreCase((String) session.getAttribute("CAPTCHA_SESSION_CODE"))) {
            log.info("验证码错误");
            return "验证码错误";
        }
        return "登录成功";
    }
}
